<template>
<div>
    <div class="upload">
      <div class="upload_warp_img" v-show="imgList.length!=0">
        <div class="upload_warp_img_div" v-for="(item,index) of imgList">
          <div class="upload_warp_img_div_top">
            <div class="upload_warp_img_div_text">
              {{item.file.name}}
            </div>
            <img v-show="!status[index].uploaded" src="./del.png" class="upload_warp_img_div_del" @click="fileDel(index)">
            <img v-show="status[index].uploaded" src="./uploaded.png" class="upload_warp_img_div_del">
          </div>
          <img :src="item.file.src">
        </div>
      </div>
      <div class="upload_warp_text">
        选中{{imgList.length}}张文件，共{{bytesToSize(this.size)}}
      </div>
      <div class="upload_warp">
        <div class="upload_warp_left" @click="fileClick">
          <img src="./upload.png">
        </div>
        <div class="upload_warp_right" @drop="drop($event)" @dragenter="dragenter($event)" @dragover="dragover($event)">
          或者将文件拖到此处
        </div>
      </div>
      <input @change="fileChange($event)" type="file" id="upload_file" multiple style="display: none"/>
      <div class="button-box">
      <mu-raised-button label="添加" :disabled="disabled" class="button button-add" @click="addPictures" />
      <mu-raised-button label="清除" class="button button-clear" @click="clearPictures" />
      </div>
    </div>
</div>
</template>
<script>
   import http from  './http.js'
  export default {
    props:['resultPictures','param','url','disabled'],
    data () {
      return {
        imgList: [],
        status:[],
        size: 0
      }
    },
      methods: {
        clearPictures:function(){
          this.imgList = []
          this.status = []
          this.size = 0
        },
          fileClick() {
              document.getElementById('upload_file').click()
          },
          fileChange(el) {
              if (!el.target.files[0].size) return;
              this.fileList(el.target);
              el.target.value = ''
          },
          fileList(fileList) {
              let files = fileList.files;
              for (let i = 0; i < files.length; i++) {
                  //判断是否为文件夹
                  if (files[i].type != '') {
                      this.fileAdd(files[i]);
                  } else {
                      //文件夹处理
                      this.folders(fileList.items[i]);
                  }
              }
          },
          //文件夹处理
          folders(files) {
              let _this = this;
              //判断是否为原生file
              if (files.kind) {
                  files = files.webkitGetAsEntry();
              }
              files.createReader().readEntries(function (file) {
                  for (let i = 0; i < file.length; i++) {
                      if (file[i].isFile) {
                          _this.foldersAdd(file[i]);
                      } else {
                          _this.folders(file[i]);
                      }
                  }
              })
          },
          foldersAdd(entry) {
              let _this = this;
              entry.file(function (file) {
                  _this.fileAdd(file)
              })
          },
          fileAdd(file) {
              //总大小
              this.size = this.size + file.size;
              //判断是否为图片文件
              if (file.type.indexOf('image') == -1) {
                  file.src = 'wenjian.png';
                  this.imgList.push({
                      file
                  });
                  this.status.push({
                    uploaded:false
                  })
                  this.$emit("update:resultPictures", this.imgList)
              } else {
                  let reader = new FileReader();
                  reader.vue = this;
                  reader.readAsDataURL(file);
                  reader.onload = function () {
                      file.src = this.result;
                      this.vue.imgList.push({
                          file
                      });
                      this.vue.status.push({
                        uploaded:false
                      })
                      this.vue.$emit("update:resultPictures", this.vue.imgList)
                  }
              }
          },
          fileDel(index) {
              this.size = this.size - this.imgList[index].file.size;//总大小
              this.imgList.splice(index, 1);
              this.status.splice(index, 1);
          },
          bytesToSize(bytes) {
              if (bytes === 0) return '0 B';
              let k = 1000, // or 1024
                  sizes = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'],
                  i = Math.floor(Math.log(bytes) / Math.log(k));
              return (bytes / Math.pow(k, i)).toPrecision(3) + ' ' + sizes[i];
          },
          dragenter(el) {
              el.stopPropagation();
              el.preventDefault();
          },
          dragover(el) {
              el.stopPropagation();
              el.preventDefault();
          },
          drop(el) {
              el.stopPropagation();
              el.preventDefault();
              this.fileList(el.dataTransfer);
          },
          //添加图片
          addPictures: function(){
            // console.log(this.param)
            if(this.imgList.length > 0){
              var that = this
              var indexArr = []
              var indexNumber = 0
              for(var i in this.imgList){
                let param = new FormData(); //创建form对象
                param.append('image',this.imgList[i].file,this.imgList[i].file.name);
                 console.log(param.get('image')) // FormData私有类对象，访问不到，可以通过get判断值是否传进去
                for(var item in that.param)
                  param.append(item,that.param[item]);
                let config = {
                  headers:{'Content-Type':'multipart/form-data'}
                }; 
                indexArr.push(i)
                http.post(that.url,param,config)
                .then(function(response){
                  console.log(response)
                  if(response.data.code == 200){
                    var index = indexArr[indexNumber]
                    indexNumber++
                    that.status[index].uploaded = true
                  }else{

                  }
                })
                .catch(function(err){console.log(err)});
              }
            }
          },
      }
  }
</script>
<style lang='css'>
    .upload_warp_img_div_del {
      position: absolute;
      top: 6px;
      width: 16px;
      right: 4px;
    }

    .upload_warp_img_div_top {
      position: absolute;
      top: 0;
      width: 100%;
      height: 30px;
      background-color: rgba(0, 0, 0, 0.4);
      line-height: 30px;
      text-align: left;
      color: #fff;
      font-size: 12px;
      text-indent: 4px;
    }

    .upload_warp_img_div_text {
      white-space: nowrap;
      width: 80%;
      overflow: hidden;
      text-overflow: ellipsis;
    }

    .upload_warp_img_div img {
      max-width: 100%;
      max-height: 100%;
      vertical-align: middle;
    }

    .upload_warp_img_div {
      position: relative;
      height: 176px;
      width: 250px;
      border: 1px solid #ccc;
      margin: 0px 10px 20px 0px;
      float: left;
      line-height: 100px;
      display: table-cell;
      text-align: center;
      background-color: #eee;
      cursor: pointer;
    }

    .upload_warp_img {
      position: relative;
      border-top: 1px solid #D2D2D2;
      padding: 14px 0 0 14px;
      overflow: hidden
    }

    .upload_warp_text {
      text-align: left;
      margin-bottom: 10px;
      padding-top: 10px;
      text-indent: 14px;
      border-top: 1px solid #ccc;
      font-size: 14px;
    }

    .upload_warp_right {
      float: left;
      width: 57%;
      margin-left: 2%;
      height: 100%;
      border: 1px dashed #999;
      border-radius: 4px;
      line-height: 130px;
      color: #999;
    }

    .upload_warp_left img {
      margin-top: 32px;
    }

    .upload_warp_left {
      text-align: center;
      float: left;
      width: 130px;
      height: 130px;
      border: 1px dashed #999;
      border-radius: 4px;
      cursor: pointer;
    }

    .upload_warp {
      margin: 14px;
      height: 130px;
    }

    .upload {
      border: 1px solid #ccc;
      background-color: #fff;
      width: 100%;
      box-shadow: 0px 1px 0px #ccc;
      border-radius: 4px;
    }
    .button-box{
      display: flex;
    }
    .button{
      width: 50%;
    }
    .button-add{
      background: #03a9f4;      
    }
    .button-clear{
      background: #FF5252;      
    }
  </style>